home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / pyshared / UpdateManager / Core / utils.py < prev   
Encoding:
Python Source  |  2009-04-27  |  7.7 KB  |  246 lines

  1. # utils.py 
  2. #  
  3. #  Copyright (c) 2004-2008 Canonical
  4. #  
  5. #  Author: Michael Vogt <mvo@debian.org>
  6. #  This program is free software; you can redistribute it and/or 
  7. #  modify it under the terms of the GNU General Public License as 
  8. #  published by the Free Software Foundation; either version 2 of the
  9. #  License, or (at your option) any later version.
  10. #  This program is distributed in the hope that it will be useful,
  11. #  but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. #  GNU General Public License for more details.
  14. #  You should have received a copy of the GNU General Public License
  15. #  along with this program; if not, write to the Free Software
  16. #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  17. #  USA
  18.  
  19. from gettext import gettext as _
  20. import locale
  21. import os
  22. import apt_pkg
  23. import urllib2
  24.  
  25. def country_mirror():
  26.   " helper to get the country mirror from the current locale "
  27.   # special cases go here
  28.   lang_mirror = { 'c'     : '',
  29.                 }
  30.   # no lang, no mirror
  31.   if not os.environ.has_key('LANG'):
  32.     return ''
  33.   lang = os.environ['LANG'].lower()
  34.   # check if it is a special case
  35.   if lang_mirror.has_key(lang[:5]):
  36.     return lang_mirror[lang[:5]]
  37.   # now check for the most comon form (en_US.UTF-8)
  38.   if "_" in lang:
  39.     country = lang.split(".")[0].split("_")[1]
  40.     if "@" in country:
  41.        country = country.split("@")[0]
  42.     return country+"."
  43.   else:
  44.     return lang[:2]+"."
  45.   return ''
  46.  
  47. def get_dist():
  48.   " return the codename of the current runing distro "
  49.   from subprocess import Popen, PIPE
  50.   p = Popen(["lsb_release","-c","-s"],stdout=PIPE)
  51.   res = p.wait()
  52.   if res != 0:
  53.     sys.stderr.write("lsb_release returned exitcode: %i\n" % res)
  54.     return "unknown distribution"
  55.   dist = p.stdout.readline().strip()
  56.   return dist
  57.  
  58. def url_downloadable(uri, debug_func=None):
  59.   """
  60.   helper that checks if the given uri exists and is downloadable
  61.   (supports optional debug_func function handler to support 
  62.    e.g. logging)
  63.  
  64.   Supports http (via HEAD) and ftp (via size request)
  65.   """
  66.   if debug_func:
  67.     debug_func("url_downloadable: %s" % uri)
  68.   import urlparse
  69.   (scheme, netloc, path, querry, fragment) = urlparse.urlsplit(uri)
  70.   if scheme == "http":
  71.     import httplib
  72.     try:
  73.       c = httplib.HTTPConnection(netloc)
  74.       c.request("HEAD", path)
  75.       res = c.getresponse()
  76.       if debug_func:
  77.         debug_func("url_downloadable result '%s'" % res.status)
  78.       res.close()
  79.       if res.status == 200:
  80.         return True
  81.     except Exception, e:
  82.       debug_func("error from httplib: '%s'" % e)
  83.       return False
  84.   elif scheme == "ftp":
  85.     import ftplib
  86.     try:
  87.       f = ftplib.FTP(netloc)
  88.       f.login()
  89.       f.cwd(os.path.dirname(path))
  90.       size = f.size(os.path.basename(path))
  91.       f.quit()
  92.       if debug_func:
  93.         debug_func("ftplib.size() returned: %s" % size)
  94.       if size != 0:
  95.         return True
  96.     except Exception, e:
  97.       if debug_func:
  98.         debug_func("error from ftplib: '%s'" % e)
  99.       return False
  100.   return False
  101.  
  102. def init_proxy(gconfclient=None):
  103.   """ init proxy settings 
  104.  
  105.   * first check for http_proxy environment (always wins),
  106.   * then check the apt.conf http proxy, 
  107.   * then look into synaptics conffile
  108.   * then into gconf  (if gconfclient was supplied)
  109.   """
  110.   SYNAPTIC_CONF_FILE = "/root/.synaptic/synaptic.conf"
  111.   proxy = None
  112.   # generic apt config wins
  113.   apt_pkg.InitConfig()
  114.   if apt_pkg.Config.Find("Acquire::http::Proxy") != '':
  115.     proxy = apt_pkg.Config.Find("Acquire::http::Proxy")
  116.   # then synaptic
  117.   elif os.path.exists(SYNAPTIC_CONF_FILE):
  118.     cnf = apt_pkg.newConfiguration()
  119.     apt_pkg.ReadConfigFile(cnf, SYNAPTIC_CONF_FILE)
  120.     use_proxy = cnf.FindB("Synaptic::useProxy", False)
  121.     if use_proxy:
  122.       proxy_host = cnf.Find("Synaptic::httpProxy")
  123.       proxy_port = str(cnf.FindI("Synaptic::httpProxyPort"))
  124.       if proxy_host and proxy_port:
  125.         proxy = "http://%s:%s/" % (proxy_host, proxy_port)
  126.   # then gconf
  127.   elif gconfclient:
  128.     try: # see LP: #281248
  129.       if gconfclient.get_bool("/system/http_proxy/use_http_proxy"):
  130.         host = gconfclient.get_string("/system/http_proxy/host")
  131.         port = gconfclient.get_int("/system/http_proxy/port")
  132.         use_auth = gconfclient.get_bool("/system/http_proxy/use_authentication")
  133.         if host and port:
  134.           if use_auth:
  135.             auth_user = gconfclient.get_string("/system/http_proxy/authentication_user")
  136.             auth_pw = gconfclient.get_string("/system/http_proxy/authentication_password")
  137.             proxy = "http://%s:%s@%s:%s/" % (auth_user,auth_pw,host, port)
  138.           else:
  139.             proxy = "http://%s:%s/" % (host, port)
  140.     except Exception, e:
  141.       print "error from gconf: %s" % e
  142.   # if we have a proxy, set it
  143.   if proxy:
  144.     # basic verification
  145.     if not proxy.startswith("http://"):
  146.       return
  147.     proxy_support = urllib2.ProxyHandler({"http":proxy})
  148.     opener = urllib2.build_opener(proxy_support)
  149.     urllib2.install_opener(opener)
  150.     os.putenv("http_proxy",proxy)
  151.  
  152. def _inhibit_sleep_old_interface():
  153.   """
  154.   Send a dbus signal to org.gnome.PowerManager to not suspend
  155.   the system, this is to support upgrades from pre-gutsy g-p-m
  156.   """
  157.   import dbus
  158.   bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
  159.   devobj = bus.get_object('org.gnome.PowerManager', 
  160.                           '/org/gnome/PowerManager')
  161.   dev = dbus.Interface(devobj, "org.gnome.PowerManager")
  162.   cookie = dev.Inhibit('UpdateManager', 'Updating system')
  163.   return (dev, cookie)
  164.  
  165. def _inhibit_sleep_new_interface():
  166.   """
  167.   Send a dbus signal to gnome-power-manager to not suspend
  168.   the system
  169.   """
  170.   import dbus
  171.   bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
  172.   devobj = bus.get_object('org.freedesktop.PowerManagement', 
  173.                           '/org/freedesktop/PowerManagement/Inhibit')
  174.   dev = dbus.Interface(devobj, "org.freedesktop.PowerManagement.Inhibit")
  175.   cookie = dev.Inhibit('UpdateManager', 'Updating system')
  176.   return (dev, cookie)
  177.  
  178. def inhibit_sleep():
  179.   """
  180.   Send a dbus signal to power-manager to not suspend
  181.   the system, try both the new freedesktop and the
  182.   old gnome dbus interface
  183.   """
  184.   try:
  185.     return _inhibit_sleep_old_interface()
  186.   except Exception, e:
  187.     try:
  188.       return _inhibit_sleep_new_interface()
  189.     except Exception, e:
  190.       #print "could not send the dbus Inhibit signal: %s" % e
  191.       return (False, False)
  192.  
  193. def allow_sleep(dev, cookie):
  194.   """Send a dbus signal to gnome-power-manager to allow a suspending
  195.   the system"""
  196.   try:
  197.     dev.UnInhibit(cookie)
  198.   except Exception, e:
  199.     print "could not send the dbus UnInhibit signal: %s" % e
  200.  
  201.  
  202. def str_to_bool(str):
  203.   if str == "0" or str.upper() == "FALSE":
  204.     return False
  205.   return True
  206.  
  207. def utf8(str):
  208.   return unicode(str, 'latin1').encode('utf-8')
  209.  
  210. def error(parent, summary, message):
  211.   import gtk
  212.   d = gtk.MessageDialog(parent=parent,
  213.                         flags=gtk.DIALOG_MODAL,
  214.                         type=gtk.MESSAGE_ERROR,
  215.                         buttons=gtk.BUTTONS_CLOSE)
  216.   d.set_markup("<big><b>%s</b></big>\n\n%s" % (summary, message))
  217.   d.realize()
  218.   d.window.set_functions(gtk.gdk.FUNC_MOVE)
  219.   d.set_title("")
  220.   res = d.run()
  221.   d.destroy()
  222.   return False
  223.  
  224. def humanize_size(bytes):
  225.     """
  226.     Convert a given size in bytes to a nicer better readable unit
  227.     """
  228.     if bytes == 0:
  229.         # TRANSLATORS: download size is 0
  230.         return _("0 KB")
  231.     elif bytes < 1024:
  232.         # TRANSLATORS: download size of very small updates
  233.         return _("1 KB")
  234.     elif bytes < 1024 * 1024:
  235.         # TRANSLATORS: download size of small updates, e.g. "250 KB"
  236.         return locale.format(_("%.0f KB"), bytes/1024)
  237.     else:
  238.         # TRANSLATORS: download size of updates, e.g. "2.3 MB"
  239.         return locale.format(_("%.1f MB"), bytes / 1024 / 1024)
  240.  
  241. if __name__ == "__main__":
  242.   print mirror_from_sources_list()
  243.